<template slot="header" slot-scope="scope">
  <div class="home">
     <div class="left">
        <div class="title">
            <div  class="titleItem active">{{state.taskTitle}}</div>
        </div>
        <div class="content">
                <el-form :model="state.formObj" :rules="state.rules" ref="ruleForm" label-width="100px" >
                      <el-form-item label="任务标题:" prop="title">
                        <el-input size="small"  placeholder="给标题起个名字" style="width: 468px;" v-model="state.formObj.title"></el-input>
                      </el-form-item>
                    <el-form-item label="简介:" prop="notice_detail">
                      <el-input  type="textarea" :rows="2" size="small" placeholder="用于展示在列表" style="width: 468px;" v-model="state.formObj.synopsis"></el-input>
                    </el-form-item>
                      <el-form-item label="任务详情:" prop="data">
                        <div style="width: 500px;">
                            <vue-ueditor-wrap v-model="state.formObj.data" :config="editorConfig" editor-id="editor-demo-01"></vue-ueditor-wrap>
                        </div>
                      </el-form-item>

                      <el-form-item label="参考资料:" >
                        <upload-file ref="uploadFile"></upload-file>
                        <el-dialog v-model="state.dialogVisible">
                          <img width="100%" :src="state.dialogImageUrl" alt="">
                        </el-dialog>
                      </el-form-item>

                      <el-form-item label="类型" prop="task_type">
                         <el-select size="small" v-model="state.formObj.task_type" placeholder="请选择类型">
                            <el-option label="基础任务" :value="1"></el-option>
                            <el-option label="实践经验" :value="2"></el-option>
                            <el-option label="拓展任务" :value="3"></el-option>
                            <el-option label="知识库" :value="4"></el-option>
                         </el-select>
                      </el-form-item>

                      <el-form-item label="奖励方式:" prop="type" v-if="state.formObj.task_type!=4">
                        <el-radio-group v-model="state.formObj.type">
                          <el-radio  :label="1">现金奖励</el-radio>
                          <el-radio  :label="2">积分奖励</el-radio>
                        </el-radio-group>
                      </el-form-item>

                      <el-form-item>
                          <el-input size="small" type="number" v-if="state.formObj.type==1" style="width: 468px;" v-model="state.formObj.money" placeholder="请输入现金"></el-input>
                          <el-input size="small" type="number" v-if="state.formObj.type==2" style="width: 468px;" v-model="state.formObj.integral" placeholder="请输入积分"></el-input>
                      </el-form-item>

                    <el-form-item label="所属分类:" prop="ktype" v-if="state.formObj.task_type == 4">
                      <el-radio-group v-model="state.formObj.ktype">
                        <el-radio  :label="1">技术部</el-radio>
                        <el-radio  :label="2">运营部</el-radio>
                        <el-radio  :label="3">商务部</el-radio>
                        <el-radio  :label="4">市场部</el-radio>
                      </el-radio-group>
                    </el-form-item>

                  <el-form-item label="指定部门权限:">
                    <span style="color: red">指定部门【所有人】可看，优先级1</span>
                    <div class="tree">
                      <el-tree
                        :data="state.department"
                        show-checkbox
                        node-key="id"
                        :default-expanded-keys="state.list_key"
                        :default-checked-keys="state.list_key"
                        ref="detree"
                        :collapse-tags="true"
                      >
                      </el-tree>
                    </div>
                  </el-form-item>

                    <el-form-item label="单独设定人员:">
                      <span style="color: red">指定人【勾选者可看】可看，优先级2</span>
                      <div class="tree">
                        <el-tree
                          :data="state.selectData"
                          show-checkbox
                          node-key="id"
                          :default-expanded-keys="state.defaultExpandedKeys"
                          :default-checked-keys="state.defaultExpandedKeys"
                          ref="tree"
                          :collapse-tags="true"
                        >
                        </el-tree>
                      </div>
                    </el-form-item>

                </el-form>
                <div style="margin-top: 20px;display: flex;margin-bottom: 40px; justify-content: center;">
                   <el-button  size="small" style="margin-right: 24px;" type="primary" @click="submitForm('ruleForm')">发布</el-button>
                   <el-button  size="small" @click="cancel">取消</el-button>
                </div>
        </div>
     </div>
  </div>
</template>
<script>
// vue3 弃用了beforeCreate created
import { getCurrentInstance, ref, reactive, onMounted, onUpdated, onUnmounted, unref } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import uploadFile from '@/components/uploadFile/uploadFile'

const state = reactive({
  headerObj:{
    Token : window.localStorage.getItem('token')
  },
  activeTab : 1,
  disabled: false,
  dialogVisible: false,
  dialogImageUrl: '',
  taskTitle: '发布任务',
  isIndeterminate: true,
  defaultExpandedKeys: [],
  defaultCheckedKeys: [],
  defaultProps: {
  },
  department: [],
  checkAll: false,
  formObj : {
    status: '1',
    title : '',
    data : '',
    integral:'0',
    money : '0.00',
    task_type: '',
    type: 0,
    about_file:'',
    synopsis: '',
    user_arr: [],
    ktype: 0,
    department: []
  },
  list_key: '',
  departmentKeys: [],
  selectData: [

  ],
  rules:{
        title: [
          { required: true, message: '请输入任务标题', trigger: 'blur' }
        ],
        data: [
          { required: true, message: '请输入任务详情', trigger: 'blur' }
        ],
        synopsis: [
          { required: true, message: '请输入任务简介', trigger: 'blur' }
        ],
        task_type: [
          { required: true, message: '请选类型', trigger: 'change' }
        ]
  }
});
export default {
  name: 'ReleaseTask',
  components: {uploadFile},
  created () {
    this.editorConfig = {
      // 更多 UEditor 配置，参考 http://fex.baidu.com/ueditor/#start-config
      // 访问 UEditor 静态资源的根路径，可参考 https://hc199421.gitee.io/vue-ueditor-wrap/#/faq
      UEDITOR_HOME_URL: '/UEditor/',
        // 服务端接口（这个地址是我为了方便各位体验文件上传功能搭建的临时接口，请勿在生产环境使用！！！）
        serverUrl: 'http://inter.huanxingbi.cn/ueditor/php/controller.php',
        toolbars: [[
        'justifyjustify', 'undo', 'bold', '|', 'simpleupload', 'forecolor', 'justifycenter',
        'justifyleft', 'horizontal', 'indent', 'fontsize', 'fontfamily'
      ]]
    }
  },
  setup(props,{emit}){
    const {ctx,proxy} = getCurrentInstance();
    const cc = getCurrentInstance();
    const _this = cc.appContext.config.globalProperties
    const store = useStore();
    const router = useRouter()
    const msg = ref('');
    const id = router.currentRoute.value.query.id;

    function cancel(){
        closeCurrentPage()
    }
    function closeCurrentPage(){
        let title = router.currentRoute.value.meta.title
        let index = store.state.contentTabs.findIndex((item)=>{
            return item.title==title
        })
        store.state.contentTabs.splice(index,1)
        let url = 'knowledge-basic-list'
        if(state.formObj.task_type == 1){
            url = 'knowledge-basic-list'
        } else if(state.formObj.task_type == 2){
            url = 'practice-list'
        } else if(state.formObj.task_type == 3){
            url = 'knowledge-basi-list'
        } else if(state.formObj.task_type == 4){
          url = 'knowledge-base-list'
        }
        window.location.href = 'http://intr.huanxingbi.cn/' + url

    }
    function submitForm(){
      proxy.$refs.ruleForm.validate((valid) => {
          if (valid) {
            let rules = proxy.$refs.tree.getCheckedKeys();
            let detree = proxy.$refs.detree.getCheckedKeys();
            let data = '*'
            let bmdata = ''
            if(rules.length > 0) {
                data = userArr(rules);
            }
            if(detree.length > 0){
                bmdata = userArr(detree);
                state.formObj.department = bmdata
            }
            state.formObj.about_file = proxy.$refs.uploadFile.state.files
            state.formObj.user_arr = data;
            if( state.formObj.type==1){
              state.formObj.integral = '0'
            }else if(state.formObj.type==2){
              state.formObj.money = '0.00'
            }
            if(state.formObj.task_type == 4 && state.formObj.ktype == 0){
                proxy.$message.error('类型为知识库的，必须选择一个所属分类')
                return false
            }
            if(id > 0){
              state.formObj.task_id = id
              _this.$request({
                url: "?s=Learn.Task.EditTask",
                params: state.formObj,
              }).then(res => {
                if (res.ret == 200) {
                  proxy.$message.success('修改成功！')
                  closeCurrentPage()
                } else {
                  proxy.$message.error(res.msg)
                }
              })
            }else {
              _this.$request({
                url: "?s=Learn.Task.PushTask",
                params: state.formObj,
              }).then(res => {
                if (res.ret == 200) {
                  proxy.$message.success('发布任务成功！')
                  closeCurrentPage()
                } else {
                  proxy.$message.error(res.msg)
                }
              })
            }
          } else {
            proxy.$message.error('请先填写表单信息！')
          return false;
         }
       });
    };
    const getDetail = () => {
      _this.$request({
        url: "?s=Learn.Task.TaskRow",
        params: {task_id:id}
      }).then(res=>{
        state.formObj = res.data
        if(res.data.user_arr!='*') {
            let str = res.data.user_arr.substr(0, res.data.user_arr.length - 1);
            state.defaultExpandedKeys = str.split(',')
        }
      })
    }
    if(id > 0){
      getDetail()
    }


    const getDeparlist = () => {
      _this.$request({
        url: "?s=Learn.Department.treeList",
        params: {pageSize:100}
      }).then(res=>{
          state.selectData   = res.data.list
          state.department = res.data.data
          let str = res.data.list_key.substr(0, res.data.list_key.length - 1);
          state.formObj.department = str
          state.list_key = str.split(',')
      })
    }

    const userArr = (data) => {
        let arr = []
        for (let i = 0;data.length > i;i++){
            if(data[i] > 0){
              arr.push(data[i]);
            }
        }
        return arr.join(',');
    }
    const changeValue = () => {

    }
    onMounted(()=>{
        //获取部门
        getDeparlist()
    });
    return{
      state,
      cancel,
      submitForm,
      msg,
      getDetail,
      userArr,
      changeValue
    }
  },
    mounted(){
    // alert(11)
  },
  activated(){
    // alert(22)
  }
}
</script>
<style lang="scss" scoped>
  .tree {
    margin-top: 8px;
  }
  /deep/.el-form-item__content {
    line-height: 40px;
    position: relative;
    font-size: 14px;
    width: 500px !important;
  }
/deep/ .edui-default .edui-toolbar .edui-button .edui-state-checked .edui-button-wrap {
  background-color: #ffe69f;
  height: 20px;
  padding: 0;
  border: 1px solid #dcac6c;
  border-radius: 2px;
  -webkit-border-radius: 2px;
  -moz-border-radius: 2px;
}
/deep/.edui-default .edui-toolbar .edui-combox .edui-combox-body{
  border: 1px solid #CCC;
  background-color: white;
  border-radius: 2px;
  -webkit-border-radius: 2px;
  height: 20px;
}
/deep/.edui-default .edui-editor-toolbarboxinner{
  height: 27px;
}
.home {
  display: flex;
  width: 100%;
   .left {
      flex: 2;
      background-color: #fff;
      height: 100%;
      margin-right: 24px;
      padding-bottom: 30px;
      .title {
        display: flex;
        border-bottom: 1px solid #E9E9E9;
        box-sizing: border-box;
        align-items: center;
        height: 55px;
          .active{
            // border-bottom: 2px solid #1890FFFF;
            color: #1890FFFF !important;
            position: relative;
          }
          .active:after{
            content:'';
            position: absolute;
            bottom: -102%;
            left: 0%;
            height: 2px;
            width: 50px;
            background-color: #1890FFFF;
          }
          .titleItem {
            margin-left: 32px;
            font-size: 16px;
            font-weight: 600;
            color: #888888FF;
            cursor: pointer;
          }
      }

      .content{
        margin-top: 22px;
        display: grid;
        place-items: center;
        overflow-y: scroll;
        //height: calc( 100vh - 300px );

      }

   }
}
</style>
